﻿
using System;
using System.Data.SqlClient;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using NSQLObjects.Filter;
using NSQLObjects.Persistence;

namespace NSQLObjectsTests.DBModel
{
    public static class CustomFilters
    {
        public static IFilterableList<T> InRange<T>(this IFilterableList<T> filterable, Expression<Func<T, object>> propertyExpression, 
            long minValue, long maxValue) where T : new()
        {
            var prop = FilterExtensions.ParseProperty<T>(propertyExpression, true);
            RangeFilter rf = new RangeFilter(prop, minValue, maxValue);
            filterable.AddFilter(rf);
            return filterable;
        }
    }

    public class RangeFilter: FilterBase
    {
        public RangeFilter(PropertyInfo targetProperty, long minValue, long maxValue):base(targetProperty)
        {
            this.MaxValue = maxValue;
            this.MinValue = minValue;
        }

        public long MinValue { get; set; }

        public long MaxValue { get; set; }

        public override string GetFilterSQL(SqlCommand cmdToBuild, string parameterPrefix)
        {

            SqlParameter par = new SqlParameter();
            par.ParameterName = parameterPrefix + "_min";
            par.ToSql(MinValue);
            cmdToBuild.Parameters.Add(par);
            par = new SqlParameter();
            par.ParameterName = parameterPrefix + "_max";
            par.ToSql(MaxValue);
            cmdToBuild.Parameters.Add(par);

            StringBuilder sqlBuilder = new StringBuilder();
            AppendProperty(sqlBuilder);
            sqlBuilder.AppendFormat(" >= @{0}_min and ", parameterPrefix); 
            AppendProperty(sqlBuilder);
            sqlBuilder.AppendFormat(" <= @{0}_max", parameterPrefix);
            return sqlBuilder.ToString();
        }
    }
}
